package com.carlife.ui;

import java.math.BigDecimal;
import java.util.Iterator;
import java.util.List;

import com.carlife.CarLife;
import com.carlife.R;
import com.carlife.model.MileageLog;
import com.carlife.model.MyCar;
import com.carlife.model.OilLog;
import com.carlife.provider.Conditions;
import com.carlife.provider.IModel;
import com.carlife.provider.MileageLogMgr;
import com.carlife.provider.OilLogMgr;
import com.carlife.ui.widget.DigitalBar;
import com.carlife.util.Constants;
import com.carlife.util.DateUtil;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class OilInput extends Activity implements View.OnClickListener {
	
	private DigitalBar oilBar = null;
	private DigitalBar priceBar = null;
	private DigitalBar moneyBar = null;
	
	
	static void show(Context context) {
        final Intent intent = new Intent(context, OilInput.class);
        context.startActivity(intent);
    }
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.oil_input);        
        setupViews();   
    }
    
    
    protected void setupViews() {
    	oilBar = (DigitalBar)findViewById(R.id.db_oil);
    	BigDecimal defaultValueOil = new BigDecimal(10.0);
    	defaultValueOil.setScale(1, BigDecimal.ROUND_HALF_DOWN);
    	oilBar.setValue(defaultValueOil);
    	oilBar.setInterval(new BigDecimal(0.5));
    	oilBar.setUnitString(getString(R.string.unit_oil));
    	oilBar.setOnValueChangedListener(new OilInputChangeListener(this));
    	
    	priceBar = (DigitalBar)findViewById(R.id.db_price);
    	BigDecimal defaultValuePrice = new BigDecimal(4.75);
    	defaultValuePrice.setScale(2, BigDecimal.ROUND_HALF_DOWN);
    	priceBar.setValue(defaultValuePrice);
    	priceBar.setInterval(new BigDecimal(0.01));
    	priceBar.setUnitString(getString(R.string.unit_price));
    	priceBar.setOnValueChangedListener(new OilInputChangeListener(this));
    	
    	moneyBar = (DigitalBar)findViewById(R.id.db_total);
    	BigDecimal defaultValueTotal = new BigDecimal(200);
    	defaultValueTotal.setScale(1, BigDecimal.ROUND_HALF_DOWN);
    	moneyBar.setValue(defaultValueTotal);
    	moneyBar.setInterval(new BigDecimal(0.1));
    	moneyBar.setUnitString(getString(R.string.unit_rmb));
    	moneyBar.setOnValueChangedListener(new OilInputChangeListener(this));
    	
    	Button btnOk = (Button)findViewById(R.id.oi_ok);
    	btnOk.setOnClickListener(this);
    	
    	Button btnCancel = (Button)findViewById(R.id.oi_cancel);
    	btnCancel.setOnClickListener(this);
    	
    	showOilLogTable();
    }
    
    /**
     * 根据加油记录显示table
     */
    private void showOilLogTable() {
    	// TODO
    	TableLayout table = (TableLayout)findViewById(R.id.oi_table_oil);
    	OilLogMgr mgr = new OilLogMgr(this);
    	OilLog model = new OilLog();
    	Conditions cond = new Conditions();
    	cond.addOrder(OilLog.FD_INPUT_TIME, false);
    	List<IModel> modelList = mgr.query(model, cond);
    	
    	Iterator iterator = modelList.iterator();
    	while(iterator.hasNext()) {
    		OilLog log = (OilLog) iterator.next();
			table.addView(concreatTableRow(log));
		}    	
    }
    
    /**
     * 根据一个加油记录显示table中的一行
     */
    private TableRow concreatTableRow(OilLog log) {
    	Log.d(Constants.LOG_TAG, log.toString());
    	TableRow row = new TableRow(this);
    	
    	// 日期
    	TextView dataTxt = new TextView(this);
    	dataTxt.setId(1);    	
    	dataTxt.setPadding(5, 5, 5, 5);
    	dataTxt.setText(DateUtil.parseToFormat(log.get(log.FD_INPUT_TIME).toString(), DateUtil.DF_SHOW));
    	row.addView(dataTxt);
    	
    	// 加油数值（升）
    	TextView quantityTxt = new TextView(this);
    	quantityTxt.setId(2);    	
    	quantityTxt.setPadding(5, 5, 5, 5);
    	quantityTxt.setText(log.get(log.FD_OIL_QUANTITY).toString());
    	row.addView(quantityTxt);
    	
    	// 油价
    	TextView priceTxt = new TextView(this);
    	priceTxt.setId(3);    	
    	priceTxt.setPadding(5, 5, 5, 5);
    	priceTxt.setText(log.get(log.FD_UNIT_PRICE).toString());
    	row.addView(priceTxt);
    	
    	// 加油总价
    	TextView moneyTxt = new TextView(this);
    	moneyTxt.setId(4);    	
    	moneyTxt.setPadding(5, 5, 5, 5);
    	moneyTxt.setText(log.get(log.FD_OIL_MONEY).toString());
    	row.addView(moneyTxt);
    	
//    	// 编辑图标
//    	ImageView removeSymbolImg = new ImageView(this);
//    	removeSymbolImg.setPadding(5, 5, 5, 5);
//    	removeSymbolImg.setImageResource(R.drawable.close_button);
//    	removeSymbolImg.setOnClickListener(new View.OnClickListener() {
//	            public void onClick(View view) { 
//	            	// TODO
//	            }           
//	        });
//		row.addView(removeSymbolImg);
    	
    	return row;
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.oillife, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch (item.getItemId()) {
	        case R.id.menu_item_home:
	            Welcome.show(this);
	            return true;
	        case R.id.menu_item_oil_input:
	            // OilInput.show(this);
	            return true;
	        case R.id.menu_item_mileage_input:
	        	MileageInput.show(this);
	            return true;
	        case R.id.menu_item_statics:
	        	MileageLineChart.show(this);
	            return true; 
        }

        return super.onMenuItemSelected(featureId, item);
    }
    
    /**
     * 响应按钮事件
     */    
    @Override
	public void onClick(View clickFocus) {
    	switch (clickFocus.getId()) {
		case R.id.oi_ok:   // 确认按钮的响应
			doSaveOilLog();
			break;
		case R.id.mi_cancel: // 取消按钮的响应
			// TODO
			break;
		default:
			break;
		}
	}
    
    private void doSaveOilLog() {
    	OilLogMgr mgr = new OilLogMgr(this);
    	OilLog model = new OilLog();
    	model.put(OilLog.FD_CAR_NO, MyCar.DUMMY_NO);
    	model.put(OilLog.FD_INPUT_TIME, DateUtil.currentTimeFormatted());
    	model.put(OilLog.FD_OIL_TYPE, OilLog.OIL_TYPE_93);
    	model.put(OilLog.FD_OIL_QUANTITY, this.oilBar.getValue().toPlainString());    	
    	model.put(OilLog.FD_UNIT_PRICE, this.priceBar.getValue().toPlainString());
    	model.put(OilLog.FD_OIL_MONEY, this.moneyBar.getValue().toPlainString());
    	mgr.insert(model);
    	
    	Welcome.show(this);    	
    }

	protected void refreshValue(View changeFocus) {
    	BigDecimal oil = this.oilBar.getValue();
    	BigDecimal price = this.priceBar.getValue();
    	BigDecimal money = this.moneyBar.getValue();
    	
     	switch (changeFocus.getId()) {
			case R.id.db_oil:
				money = oil.multiply(price);
				money.setScale(2, BigDecimal.ROUND_HALF_DOWN);
				this.moneyBar.setValue(money);
				break;
			case R.id.db_price:
				money = oil.multiply(price);
				money.setScale(2, BigDecimal.ROUND_HALF_DOWN);
				this.moneyBar.setValue(money);
				break;
			case R.id.db_total:
				oil = money.divide(price, 1, BigDecimal.ROUND_HALF_DOWN);
				this.oilBar.setValue(oil);	
				break;
			default:
				break;
		}
    	
    }
    
    

}
